<?php
// +----------------------------------------------------------------------
// | UCToo [ Universal Convergence Technology ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2020 http://www.uctoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Patrick <contact@uctoo.com>
// +----------------------------------------------------------------------

namespace app\wechatopen\controller;

use app\wechatopen\service\openPlatform\FullPublicMessageHandler;
use app\wechatopen\service\openPlatform\EventMessageHandler;
use think\Cache;
use think\Controller;
use EasyWeChat\Kernel\Exceptions\BadRequestException;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\OpenPlatform\Application;
use uctoo\ThinkEasyWeChat\Facade;

/**
 * 微信第三方平台交互控制器，中控服务器
 * 主要获取和反馈微信平台的数据，分析用户交互和系统消息分发。
 */
class Eventmessage extends Controller {

    //行为绑定，需要将标签位的处理逻辑分发到各个行为类的都要在这里绑定行为
    public function _initialize()
    {
    }

     /**
     * 第三方平台微信消息接口入口
     * 所有发送到微信的消息都会推送到该操作
     * 所以，微信公众平台后台填写的api地址则为该操作的访问地址
     * 在open.weixin.qq.com 第三方平台配置的 消息与事件接收URL(服务器地址)  http://域名/wechatopen/eventmessage/index/appid/$APPID$
     *
     * @param Application $app
     * @param null $appid
     * @throws BadRequestException
     * @throws InvalidArgumentException
     * @throws InvalidConfigException
     * @throws \ReflectionException
     */
	public function index($appid = null) {
        if(is_null($appid)){
            abort(404);
        }
        $applet = \app\admin\model\wechatopen\Applet::get(['appid'=>$appid]);
        if(!isset($applet)){  //未授权到第三方平台的应用
            abort(404);
        }
        session('applet_info',$applet);       //将当前会话的应用信息加入session,TODO：判断授权是否过期
        $wechatopenInfoConfig = Cache::get('wechatopen_config');
        $openPlatform = Facade::openPlatform($wechatopenInfoConfig['app_id'],$wechatopenInfoConfig);

        $preAccount = [            //微信第三方平台发布测试帐号
            'wx570bc396a51b8ff8' => 'officialAccount',
            'wxd101a85aa106f53e' => 'miniProgram',
        ];

        if(isset($preAccount[$appid])){
            $server = $openPlatform->{$preAccount[$appid]}($appid)->server;
            $server->push(new FullPublicMessageHandler($openPlatform,$appid,$preAccount[$appid]));
        }else{
            $server = $openPlatform->officialAccount($appid)->server;
            $server->push(new EventMessageHandler($appid));
        }
        $server->serve()->send();

	}
}